<?php

if (!class_exists("PST_FILE")) {

    class PST_FILE extends PST_PRESENTATION {
        
        private $folder = "files/";

        public function __construct($settings) {
            parent::__construct($settings);
            
            if (empty($this->array['type'])) {
                $this->array['type'] = "file";
            }
        }

        public function renderReadOnly() {
            if (isset($this->isvisible) && !$this->isvisible) {
                return '<input type="hidden" name="' . $this->name . '" id="' . $this->id . '" value="' . $this->value . '" />';
            }

            $subpath = "";
            for ($j = 0; $j < 5; $j++) {
                $subpath.= substr($this->value, ($j * 2), 2) . "/";
            }

            $html = '<div id="box' . $this->id . '" class="input ' . $this->array['type'] . ' ' . $this->required . '">';
            $html.= '<input type="hidden" name="' . $this->name . '" id="' . $this->id . '" value="' . $this->value . '" />';
            $html.= '<label for="' . $this->id . '">' . $this->label . '</label>';
            $html.= '<span class="field">';
            $html.= '<a href="' . WWW . $this->folder . $subpath . $this->value . '" target="_blank">';
            $html.= '<img src="' . WWW . $this->folder . $subpath . $this->value . '" width="50px" />';
            $html.= '</a>';
            $html.= '</span>';
            $html.= '</div>';
            return $html;
        }

        public function saveDbQuery() {
            if ($this->value['error'] != 0) {
                return "";
            }

            $extension = strtolower(substr($this->value['name'], strrpos($this->value['name'], ".") + 1));
            $arch = md5($this->value['name'] . time()) . "." . $extension;

            $root = WWW_ROOT . $this->folder;
            
            //Agrego 5 subniveles por el archivo
            $subpath = "";
            for ($j = 0; $j < 5; $j++) {
                $subpath.= substr($arch, ($j * 2), 2) . "/";
                if (!is_dir($root . $subpath)) {
                    mkdir($root . $subpath);
                }
            }

            if (move_uploaded_file($this->value['tmp_name'], $root . $subpath . $arch)) {
                return $arch;
            }

            return "";
        }

    }

}
